package com.beardedcoder.utils.power;

import java.util.Date;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;

public class AirplaneFeatures implements PowerFeatures {
	
	private ContentResolver resolver;
	private Context context;

	public AirplaneFeatures (Context context) {
		resolver = context.getContentResolver();
		this.context = context;
	}

	@Override
	public void deactivate() {
		 Settings.System.putInt(resolver, Settings.System.AIRPLANE_MODE_ON, 0);
		 postBroadcastSettingChanged(false);
	}

	@Override
	public void activate() {
        Settings.System.putInt(resolver, Settings.System.AIRPLANE_MODE_ON, 1);
        postBroadcastSettingChanged(true);
	}
	
	private void postBroadcastSettingChanged(boolean enabling) {
		Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        intent.putExtra("state", enabling);
        context.sendBroadcast(intent);
	}

	@Override
	public void setDeactivateAt(Date time) {
	}

	@Override
	public void setActivateAt(Date time) {
	}

	@Override
	public boolean isActive() throws SettingNotFoundException {
		return Settings.System.getInt(resolver, Settings.System.AIRPLANE_MODE_ON) == 1 ? true : false;
	}

	@Override
	public void toggleState() {
		boolean isActive = false;
		try {
			isActive = isActive();
		} catch (SettingNotFoundException e) {
			e.printStackTrace();
		}
		if (isActive) {
			deactivate();
		} else {
			activate();
		}
	}

}
